/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.office.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.office.entity.DocTemplate;
import com.jeeplus.modules.office.service.DocTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 文书模板Controller
 * @author sunyinhui
 * @version 2020-06-23
 */
@Api(tags ="文书模板")
@RestController
@RequestMapping(value = "/wps/docTemplate")
public class DocTemplateController extends BaseController {

	@Autowired
	private DocTemplateService docTemplateService;

	@ModelAttribute
	public DocTemplate get(@RequestParam(required=false) String id) {
		DocTemplate entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = docTemplateService.get(id);
		}
		if (entity == null){
			entity = new DocTemplate();
		}
		return entity;
	}

	/**
	 * 文书模板列表数据
	 */
	@ApiOperation("获取文书模板列表数据")
	@RequiresPermissions("wps:docTemplate:list")
	@GetMapping("list")
	public AjaxJson list(DocTemplate docTemplate, HttpServletRequest request, HttpServletResponse response) {
		Page<DocTemplate> page = docTemplateService.findPage(new Page<DocTemplate>(request, response), docTemplate);
		return AjaxJson.success().put("page",page);
	}

	/**
	 * 根据Id获取文书模板数据
	 */
	@ApiOperation("根据Id获取文书模板数据")
	@RequiresPermissions(value={"wps:docTemplate:view","wps:docTemplate:add","wps:docTemplate:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(DocTemplate docTemplate) {
		return AjaxJson.success().put("docTemplate", docTemplate);
	}

	/**
	 * 保存文书模板
	 */
	@ApiOperation("保存文书模板")
	@RequiresPermissions(value={"wps:docTemplate:add","wps:docTemplate:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(DocTemplate docTemplate, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(docTemplate);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		docTemplateService.save(docTemplate);//保存
		return AjaxJson.success("保存文书模板成功");
	}


	/**
	 * 保存文书模板
	 */
	@ApiOperation("获取文书模板副本")
	@PostMapping("getCopyDoc")
	public AjaxJson getCopyDoc(DocTemplate docTemplate, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(docTemplate);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		docTemplateService.save(docTemplate);//保存
		return AjaxJson.success("保存文书模板成功");
	}


	/**
	 * 批量删除文书模板
	 */
	@ApiOperation("批量删除文书模板")
	@RequiresPermissions("wps:docTemplate:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			docTemplateService.delete(docTemplateService.get(id));
		}
		return AjaxJson.success("删除文书模板成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("wps:docTemplate:export")
    @GetMapping("export")
    public AjaxJson exportFile(DocTemplate docTemplate, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "文书模板"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<DocTemplate> page = docTemplateService.findPage(new Page<DocTemplate>(request, response, -1), docTemplate);
    		new ExportExcel("文书模板", DocTemplate.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出文书模板记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("wps:docTemplate:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<DocTemplate> list = ei.getDataList(DocTemplate.class);
			for (DocTemplate docTemplate : list){
				try{
					docTemplateService.save(docTemplate);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条文书模板记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条文书模板记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入文书模板失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入文书模板数据模板
	 */
	@RequiresPermissions("wps:docTemplate:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "文书模板数据导入模板.xlsx";
    		List<DocTemplate> list = Lists.newArrayList();
    		new ExportExcel("文书模板数据", DocTemplate.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }


}
